<template>
  <div>
    <div id="ecgView">
      <svg id="ecg" width="1027" height="500"></svg>
    </div>
  </div>
</template>

<script>
import * as Ecg from './ecg'
export default {
  name: 'realTimeEcgChart',
  props: {
  },
  data() {
    return {
      parentDiv: [],
      start_time: 1509360664,
      sample: 200,
      ecgData: [],
      ws: undefined,
      ecgvalue: [],
      headerData: {
        'report_user': `姓名：张三`,
        'report_sex': '性别：男',
        'report_age': '年龄：20',
        'report_hr': 'HR：80 10mm/mV 25mm/s',
        'report_start_time': `测量时间：`,
        'report_id': '报告编号：1490951160994'
      },
    }
  },
  created() {
    this.$nextTick(() => {
      this.showEcg()
    })
    this.ws = new WebSocket('ws://47.92.88.35:10001');
    // this.ws = new WebSocket('ws://192.168.10.22:10001');
    console.log(this.ws)
    this.ws.onopen = () => {
      console.log('onopen');
      // connection opened
      this.ws.send('12345'); // send a message
    };

    // this.fetchData()
    this.connect()
  },
  methods: {
    connect() {
      this.ws.onmessage = (e) => {
        // a message was received
        console.log(e)
        console.log(e.data);
        console.log(this.ecgData)
        
        let res = JSON.parse(e.data)
        console.log(res)
        if (res.length > 0) {
          let val = res.map(item => {return item - 2048})
          let result = this.ecgData.concat(val)
          this.ecgData = result
          
          this.$nextTick(() => {
            this.showEcgByData()
          })
        }
      };
      
      this.ws.onerror = (e) => {
        // an error occurred
        console.log(e)
        console.log(e.message);
      };
      
      this.ws.onclose = (e) => {
        // connection closed
        console.log(e)
        console.log(e.code, e.reason);
      };
    },
    fetchData() {
      let res = this.ecgvalue
      this.ecgData = res.map(item => {return item - 2048})
      this.$nextTick(() => {
        this.showEcg()
        this.showEcgByData()
      })
    },
    showEcg() {
      const oEcg = document.getElementById('ecg')
      this.parentDiv.push('ecgView')
      Ecg.Ecg.init(oEcg, this.parentDiv)
      Ecg.Ecg.draw(this.headerData, this.ecgData, this.start_time, this.sample)
    },
    showEcgByData() {
      const oEcg = document.getElementById('ecg')
      var ecgDataArray = this.ecgData
      Ecg.Ecg.init(oEcg, this.parentDiv)
      Ecg.Ecg.draw(this.headerData, ecgDataArray, this.start_time, this.sample)
    }
  }
}
</script>

<style lang="scss">

</style>
